#!/usr/bin/env python
# -*- coding: utf-8 -*-
from string import Template
from tack.lib import string_app, json_app, content_headers, status_codes
from datetime import datetime, timedelta
from tack_ocie.api.util import state_def, build_empty_row_dict, build_row_dict, build_row_dict_for_sql, build_columns_values_sql, fill_dict_from_form, build_columns_values_sql


get_one = """
SELECT * FROM ocie_schedule
WHERE (state_finish IS NULL 
    AND schedule_id = $schedule_id) 
OR (state_finish IS NULL 
    AND parent_id = $schedule_id)
"""


set_state_finish = """
UPDATE ocie_schedule
SET state_finish = '$time_stamp'
WHERE schedule_id = $old_state_id
"""


get_attendee_columns = "SELECT * FROM ocie_schedule_attendee WHERE 1 = 0"


insert_state = "INSERT INTO ocie_schedule"


insert_attendee = "INSERT INTO ocie_schedule_attendee"


delete_attendee = "DELETE FROM ocie_schedule_attendee WHERE schedule_id = $schedule_id"


def update(environ, start_response, state):
    form = environ['form']
    try:
        start = datetime.strptime(form['start'],'%Y-%m-%d %H:%M')
        finish = datetime.strptime(form['finish'],'%Y-%m-%d %H:%M')
        if(start >= finish):
            raise ValueError
    except:        
        start_response(status_codes.error, content_headers.default_plain())
        return ['Error']
    schedule_id = environ['dispatcher.groups']['schedule_id']
    sql = Template(get_one).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if rows:
        cd = cursor.description
        old_state_id = rows[0].schedule_id
        throwaway = datetime.now()
        time_stamp = throwaway.strftime('%Y-%m-%d %H:%M:%S')
        state_dict = build_row_dict_for_sql(cd, rows[0])
        state_dict = fill_dict_from_form(state_dict, cd, form)
        if not state_dict['parent_id']:
            state_dict['parent_id'] = state_dict['schedule_id']
        del state_dict['schedule_id']
        state_dict['state_key'] = state
        state_dict['state_start'] = "'" + time_stamp + "'"
        del state_dict['state_finish']
        sql = insert_state + build_columns_values_sql(state_dict)
        cursor.execute(sql)
        environ['connection'].commit()
        sql = Template(set_state_finish).substitute(locals())
        cursor.execute(sql)
        environ['connection'].commit()
        form['schedule_id'] = schedule_id = state_dict['parent_id']
        sql = Template(delete_attendee).substitute(locals())
        cursor.execute(sql)
        environ['connection'].commit()
        form['attendee_ranks'] = form['attendee_ranks'] if isinstance(form['attendee_ranks'], list) else [form['attendee_ranks']]
        form['attendee_first_names'] = form['attendee_first_names'] if isinstance(form['attendee_first_names'], list) else [form['attendee_first_names']]
        form['attendee_last_names'] = form['attendee_last_names'] if isinstance(form['attendee_last_names'], list) else [form['attendee_last_names']]
        form['attendee_ssn'] = form['attendee_ssn'] if isinstance(form['attendee_ssn'], list) else [form['attendee_ssn']]
        attendees = zip(form['attendee_ranks'],form['attendee_first_names'],form['attendee_last_names'],form['attendee_ssn'])
        cursor.execute(get_attendee_columns)
        rows = cursor.fetchall()
        cd = cursor.description
        attendee_dict = build_empty_row_dict(cd)
        del attendee_dict['schedule_attendee_id']
        for attendee in attendees:
            form['rank'] = attendee[0]
            form['first_name'] = attendee[1]
            form['last_name'] = attendee[2]
            form['ssn'] = attendee[3]
            attendee_dict = fill_dict_from_form(attendee_dict, cd, form)
            sql = insert_attendee + build_columns_values_sql(attendee_dict)
            cursor.execute(sql)
            environ['connection'].commit()
        output = 'Updated'
    else:
        start_response(status_codes.not_found, content_headers.default_plain())
        return ['404 Not Found']   
    return json_app(output)(environ, start_response)


def update_rescheduled(environ, start_response):
    return update(environ, start_response, state_def.RESCHEDULED)


def update_resourced(environ, start_response):
    return update(environ, start_response, state_def.RESOURCED)
    

def update_drafted(environ, start_response):
    form = environ['form']
    try:
        start = datetime.strptime(form['start'],'%Y-%m-%d %H:%M')
        finish = datetime.strptime(form['finish'],'%Y-%m-%d %H:%M')
        if(start >= finish):
            raise ValueError
    except:        
        form['start'] = datetime.now().strftime('%Y-%m-%d %H:%M')
        form['finish'] = ( datetime.now() + timedelta(minutes=1) ).strftime('%Y-%m-%d %H:%M')
    return update(environ, start_response, state_def.DRAFTED)
